// pages/me/myBill/myBill.js
import * as echarts from '../../../template/ec-canvas/echarts';
const API = require('../../../utils/api.js');
const AJAX = require('../../../utils/ajax.js');
const DateUtils = require('../../../utils/date.js')

/**
 * 初始化图表
 */
function setOption(chart, xdata, ydata, titleName) {
  const option = {
    title: {
      text: titleName,
      left: 'center',
      textStyle: {
        fontSize: 16,
        color: '#000000',
      },
      top: '10rpx'
    },
    backgroundColor: "#fff",
    color: ["#006EFF", "#67E0E3", "#9FE6B8"],
    animation: true,
    grid: {
      show: false
    },
    tooltip: {
      show: true,
      trigger: 'axis'
    },
    xAxis: {
      type: 'category',
      data: xdata, //x轴上的数据是动态的，所以我作为参数传进来
      axisLabel: {
        interval: 4, //x轴间隔多少显示刻度
        fontSize: 7
      }
    },
    yAxis: {
      x: 'center',
      scale: true,
      type: 'value',
      axisLabel: {
        formatter: function(value) {
          var val = value + '元';
          return val
        }
      }
    },
    series: [{
      name: '今日收入',
      type: 'line',
      data: ydata, //y轴上的数据也是动态的，也作为参数传进来
      symbol: 'none',
      lineStyle: {
        width: 1
      }
    }]
  };
  chart.setOption(option)
}
/**
 * 初始化图文
 */
function setOptionPie(chart, data, titleName) {
  var option = {
    title: {
      text: titleName,
      left: 'center',
      textStyle: {
        fontSize: 16,
        color: '#000000',
      },
      top: '10rpx'
    },
    backgroundColor: "#ffffff",
    color: ["#37A2DA", "#32C5E9", "#67E0E3", "#91F2DE", "#FFDB5C", "#FF9F7F"],
    series: [{
      label: {
        normal: {
          fontSize: 14
        }
      },
      type: 'pie',
      center: ['50%', '50%'],
      radius: [0, '60%'],
      data: data,
      // itemStyle: {
      //   emphasis: {
      //     shadowBlur: 10,
      //     shadowOffsetX: 0,
      //     shadowColor: 'rgba(0, 2, 2, 0.3)'
      //   }
      // }
      itemStyle: {
        normal: {
          label: {
            show: true,
            position: 'inner',
            formatter: function (params) {
              return (params.percent - 0).toFixed(0) + '%'
            }
          },
          labelLine: {
            show: false
          }
        },
        emphasis: {
          label: {
            show: true,
            formatter: "{b}\n{d}%"
          }
        }
      }
    }]
  };
  chart.setOption(option)
}

Page({

  /**
   * 页面的初始数据
   */
  data: {
    ecline: {
      lazyLoad: true
    },
    ecPie: {
      lazyLoad: true
    },
    isPayShow: true,
    date: DateUtils.formatTime(new Date()),
    chartTitle: '每日收入',
    // X轴显示数据
    categories: [],
    // 收入数据
    incomes: [],
    // 支出数据
    pays: [],
    // 收入分类所占比重
    consumeIncomeProportion: [],
    // 支出分类所占比重
    consumePayProportion: [],
    // 当前用户消费有效日期
    billObj: {
      startTime: '2019-09-27',
      endTime: '2019-10-27'
    },
    // 支出分类标题
    chartTitleType: '收入分类',
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    // 请求统计数据信息
    this.getTimeResult(new Date().getTime());
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {
    this.lineComponent = this.selectComponent('#mychart-line');
    this.pieComponent = this.selectComponent('#mychart-pie');
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  },

  /**
   * 切换分支
   */
  tabTap: function(e) {
    console.log(e.currentTarget.dataset.type)
    let isPayShow = e.currentTarget.dataset.type === 'income' ? true : false
    let chartTitle = e.currentTarget.dataset.type === 'income' ? '每日收入' : '每日支出'
    let chartTitleType = e.currentTarget.dataset.type === 'income' ? '收入分类' : '支出分类'
    this.setData({
      isPayShow: isPayShow,
      chartTitle: chartTitle,
      chartTitleType: chartTitleType,
    })
    this.initCanvas()
  },
  /**
   * 选择时间
   */
  bindDateChange: function(e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      date: e.detail.value
    })
    // 请求数据信息
    this.getTimeResult(new Date(e.detail.value).getTime())
  },
  initCanvas: function() { //初始化第一个图表
    this.lineComponent.init((canvas, width, height) => {
      const chart = echarts.init(canvas, null, {
        width: width,
        height: height
      });
      let yData = this.data.chartTitle === '每日收入' ? this.data.incomes : this.data.pays
      setOption(chart, this.data.categories, yData, this.data.chartTitle)
      this.chart = chart;
      return chart;
    });
    this.pieComponent.init((canvas, width, height) => {
      const chart = echarts.init(canvas, null, {
        width: width,
        height: height
      });
      let data = this.data.chartTitleType === '收入分类' ? this.data.consumeIncomeProportion : this.data.consumePayProportion
      setOptionPie(chart, data, this.data.chartTitleType)
      this.chart = chart;
      return chart;
    });

  },
  getTimeResult: function(valueTime) {
    var _this = this;
    // let resultUrl = API.api.assetsDetails + '/' + wx.getStorageSync('userId') +'/' +  valueTime;
    let resultUrl = API.api.assetsDetails + '/' + wx.getStorageSync('userId') +  '/' + valueTime;
    AJAX.getRequest(resultUrl).then(response => {
      console.log(response.data)
      let resData = response.data
      let billObj = {}
      billObj.startTime = resData.billStartTime
      billObj.endTime = resData.billEndTime
      _this.setData({
        categories: resData.categories,
        incomes: resData.incomes,
        pays: resData.pays,
        consumeIncomeProportion: resData.consumeIncomeProportion,
        consumePayProportion: resData.consumePayProportion,
        billObj: billObj,
      })
      // 渲染图表信息
      _this.initCanvas()
    })
  },
})